#pragma once

#include <iostream>
#include <sstream>
#include <mysql/mysql.h>
#include "../util.hpp"
#include <stdlib.h>
#include "../http.h"
#include "operate.hpp"
#include "action.hpp"
using namespace http_server;

void HttpResponse(const string& body){
    //在这里设置Content-Type，保证设置cookie在调用此函数之前
    cout << "Content-Type: text/html; charset=utf-8" << "\n";
    cout << "Content-Length: " << body.size() << "\n";
    cout << "\n";//这个空行是header和body之间的空行
    cout << body;
}

int Init(StringUtil::UrlParam& params,MYSQL*& conn){
    //1.先获取到method
    const char* method = getenv("REQUEST_METHOD");
    if(method == NULL){
        HttpResponse("No env REQUEST_METHOD");
        return 1;
    }

    if(string(method) == "GET"){
        //2.如果是GET请求，从query_string中读取参数
        //  解析query_string中的数据
        const char* query_string = getenv("QUERY_STRING");
        StringUtil::ParseUrlParam(query_string,params);
    }else if(string(method) == "POST"){
        //3.如果是POST请求，从Content-Length中读取body的长度
        //  根据body的长度，从标准输入中读取请求的body
        //  解析body中的数据
        char buf[1024 * 10] = {0};
        read(0,buf,sizeof(buf)-1);

        StringUtil::ParseUrlParam(buf,params);
        write(0,buf,strlen(buf));
    }
    
    const char* cookie = getenv("HTTP_COOKIE");
    if(cookie)
        StringUtil::ParseCookieParam(cookie,params);
    
    DataBaseInit(conn);

    return 0;
}

void Stay(MYSQL* conn,string& output,StringUtil::UrlParam params,string user){
    string action = params["action"];
    if(action == "index")
        Action::ActionIndex(conn,output,user);
    else if(action == "display"){
        string topic = params["cookie_topic"];
        string page = params["cookie_page"];
        Action::ActionDisplay(conn,output,topic,user,page);
    }else if(action == "news"){
        string title = params["cookie_title"];
        string comment = "";
        Action::ActionNews(conn,output,title,comment,user);
    }else if(action == "search"){
        string keyword = params["cookie_keyword"];
        string page = params["cookie_page"];
        Action::ActionSearch(conn,output,keyword,user,page);
    }else
        Action::ActionIndex(conn,output,user);
}


